import { createRouter, createWebHistory, type RouteRecordRaw } from 'vue-router'
import { getRouterListApi, type RouterVO } from '@/request/api/router'
import type { ResultType } from '@/type/type'
import { useScrollStore } from '@/stores/scroll'
import { useStyleStore } from '@/stores/style'
import { RouteNameEnum, RouterEnum } from '@/enum'
import { useSystemStore } from '@/stores/system'
import { useGlobalLoading } from '@/hooks'

/*加载所有组件*/
const modules: any = import.meta.glob('../views/**/*.vue', { eager: true })
const map = new Map<string, any>()
for (const path in modules) {
  map.set(path.replace('../views', ''), modules[path].default)
}

export function getUiRouter(): RouteRecordRaw[] {
  return routeBarList[0]
}

export function getAdminRouter(): RouteRecordRaw[] {
  return routeBarList[1]
}

/*
 * 注意：该对象中的 0，1 元素分别表示 UI 端和 Admin 端路由
 */
const routeList: any = {
  0: [],
  1: []
}

const routeBarList: any = {
  0: [],
  1: []
}

// 生成动态路由
function createRoute(list: RouterVO[], parent?: any) {
  list.forEach((item) => {
    // 构建路由
    const routeItem: RouteRecordRaw = {
      path: item.path,
      name: item.name,
      meta: {
        title: item.title,
        icon: item.icon,
        name: item.name,
        isAdmin: item.isAdmin,
        isFrame: item.isFrame
      },
      children: []
    }

    if (item.component) {
      routeItem.components = {
        [item.isAdmin ? 'admin' : 'ui']: map.get(item.component) || null
      }
    }
    // 如果存在子路由，递归调用 setRoute 处理
    if (item.children && item.children.length > 0) {
      createRoute(item.children, routeItem)
    }
    // 如果有父路由，则将当前路由添加到父路由的子路由列表中
    if (parent) {
      parent.children.push(routeItem)
    } else {
      if (!item.isFrame) {
        routeList[Number(item.isAdmin)].push(routeItem)
      }
      if (item.isBar) {
        routeBarList[Number(item.isAdmin)].push(routeItem)
      }
    }
  })
}

// 获取动态路由
await getRouterListApi().then((res: ResultType<RouterVO[]>) => {
  createRoute(res.data)
})

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: RouterEnum.UI,
      name: 'root_ui',
      components: { root: () => import('@/components/UI.vue') },
      children: [...routeList[0]]
    },
    {
      path: RouterEnum.ADMIN,
      name: 'root_admin',
      components: { root: () => import('@/components/admin/Admin.vue') },
      children: [
        {
          path: '',
          name: 'default_home',
          redirect(to) {
            to.name = RouteNameEnum.ADMIN_HOME
            return to
          }
        },
        ...routeList[1]
      ]
    },
    {
      path: '/login',
      name: RouteNameEnum.LOGIN,
      components: { root: () => import('@/views/login/Login.vue') }
    }
  ]
})

let loading: null | any = null

router.beforeEach((to, from, next) => {
  // console.log(from, to)
  // 相同页面
  if (to.fullPath === from.fullPath && to.fullPath !== '/') {
    return
  }

  loading = useGlobalLoading({
    text: '数据加载中...',
    background: useStyleStore().background.bgType === 'dark' ? 'rgb(0, 0, 0)' : 'rgb(255, 255, 255)'
  })

  // 刷新时间 自动调整主题色
  useStyleStore().refreshBgColor()
  // 添加管理端面包屑
  if (to.meta.isAdmin && to.meta.title) {
    useSystemStore().system.routeMap.set(to.meta.title.toString(), to.fullPath)
  }

  const timer = setTimeout(() => {
    next()
    clearTimeout(timer)
  }, 100)
})

router.afterEach(async (to, from) => {
  // 隐藏移动端导航
  useSystemStore().system.isShowMobile = false
  // 回到顶部
  useScrollStore().toTop()
  const timer = setTimeout(() => {
    if (useScrollStore().scroll.isTop) {
      loading?.close()
      if (to.query.id != undefined) {
        const doc = document.getElementById(to.query.id.toString())
        if (doc != null) {
          useScrollStore().scroll.scrollRef.scrollTo({
            behavior: 'smooth',
            top: doc.offsetTop + doc.clientHeight - 100 || 0
          })
        }
      }
      clearTimeout(timer)
    }
  }, 500)
})
// console.log(router.getRoutes())
// console.log(routeList)
export default router
